﻿using DeviceMonitor.Model;
using DeviceMonitor.Utils;
using MPMS.Srv.WebService;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Asn1.X509;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Services.Description;
using System.Windows;
using System.Windows.Input;

namespace DeviceMonitor.ViewModel
{
    class AlermViewModel : RecordViewModel
    {
        public ObservableCollection<AlermModel> _list = new ObservableCollection<AlermModel>();
        public QueryParamModel _paramModel = new QueryParamModel();
        // 定义 UploadCommand 命令
        public ICommand UploadCommand { get; private set; }

        public AlermViewModel()
        {
            // 初始化 UploadCommand 并绑定到执行方法
            UploadCommand = new RelayCommand(OnUploadExecuted, CanExecuteUpload);
        }

        public ObservableCollection<AlermModel> list
        {
            get { return _list; }
            set
            {
                _list = value;
                RaisePropertyChanged("list");
            }
        }
        public QueryParamModel queryParam
        {
            get { return _paramModel; }
            set
            {
                _paramModel = value;
                RaisePropertyChanged("queryParam");
            }
        }
        public static String getUUID()
        {
            return System.Guid.NewGuid().ToString().Replace("-", "");
        }
        private void OnUploadExecuted(object parameter)
        {
            AlermModel alerm = (AlermModel)parameter;
            // string jsonString = parameter.ToString();
            //JObject alerm = JObject.Parse(jsonString);
            // JObject alerm = (JObject)parameter;
            string position = "";
            if (alerm.deviceId.Equals("39"))
            {
                position = "31";
            }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
            else
            {
                position = (int.Parse(alerm.deviceId) - 4).ToString();
            }
            JObject alermJson = new JObject();

            String uuid = getUUID();
            string alarmTime = alerm.createTime;
            //string alarmWord = (string)alarm["alarmword"];
            string alarmName = alerm.alermName;
            string newalarm = alerm.alerm;
            string id = (string)alerm.id;
            string carNumber = alerm.carNumber;
            string endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ;
            alermJson.Add("id", uuid);
            alermJson.Add("moduleId", id);
            alermJson.Add("groupCode", "0");
            //alermJson.Add("code", "0");
            alermJson.Add("deviceId", position);
            alermJson.Add("alerm", newalarm);
            alermJson.Add("alermName", alarmName);
            alermJson.Add("createTime", alarmTime);
            alermJson.Add("billNo", "");
            //

            DockingInfo dockingInfo = new DockingInfo();
            string resp = dockingInfo.AlarmInfo(
                  uuid,
                  id,
                  "0",
                  "东营齐润化工有限公司",
                  carNumber,
                  alarmTime,
                  position,
                  newalarm
                  );
            if (resp.Equals("true"))
            {
                alermJson.Add("code", "1");
                string timeUrl = "http://" + App.GetConfig().DBServiceIp + ":" + App.GetConfig().DBServicePort + "/alerm/updateLastQueryTime";
                JObject uploadTime = new JObject();
                uploadTime.Add("currentQueryTime", endTime);
                uploadTime.Add("type", "alerm");
                String uploadResponse = HttpPostHelper.doHttpPost(timeUrl, uploadTime.ToString());
                //}
                //else
                //{
                //    MessageBox.Show("上传失败");
                //}
                //    // 你可以在这里执行上传的操作
                //    Console.WriteLine("上传操作已执行");

                // 例如，执行数据上传的实际逻辑
                // 可以访问参数（例如 DataGrid 中选中的某一行）来上传特定的数据
                //alermJson.Add("code", "0");
                this.ServiceUpload(alermJson);//上传后端
                //string timeUrl = "http://" + App.GetConfig().DBServiceIp + ":" + App.GetConfig().DBServicePort + "/alerm/updateLastQueryTime";

                RefreshData();
            }
            else
            {
                MessageBox.Show("上传失败");
                alermJson.Add("code", "0");
                this.ServiceUpload(alermJson);
            }



        }
        public void ServiceUpload(JObject alermJson)
        {
            string alermUrl = "http://" + App.GetConfig().DBServiceIp + ":" + App.GetConfig().DBServicePort + "/alerm/insertAlerm";
            String billResponse = HttpPostHelper.doHttpPost(alermUrl, alermJson.ToString());
           //MessageBox.Show(billResponse);
        }
         private bool CanExecuteUpload(object parameter)
    {
        // 判断是否可以执行命令，可以在这里进行一些验证
        // 例如，检查是否有选择的项
        return true;  // 返回 true 表示命令可以执行
    }
        public async Task RefreshData()
        {
            // 实现刷新数据的逻辑
            var refreshedData = await GetAlermDataFromServer();  // 假设 GetAlermDataFromServer 是一个 async 方法
            list.Clear();
            foreach (var item in refreshedData)
            {
                list.Add(item);
            }

            // 通知 UI 刷新
            RaisePropertyChanged(nameof(list));
        }
        private async Task<List<AlermModel>> GetAlermDataFromServer()
        {
            // 实现从服务器获取最新数据的逻辑
            // 这里只是一个示例，假设返回一个新的 AlermModel 列表
            JObject paramJSON = new JObject();

            String response = HttpPostHelper.doHttpPost("/alerm/queryAlermList", paramJSON.ToString());
            JObject rspJson = JObject.Parse(response);
            bool success = (bool)rspJson["success"];
            if (success)
            {
                var jsonStr = rspJson["data"]["dataList"].ToString();
                JArray dataListArray = (JArray)rspJson["data"]["dataList"];
                // 将 JArray 反序列化为 List<MyDataClass>
                List<AlermModel> dataList = JsonConvert.DeserializeObject<List<AlermModel>>(dataListArray.ToString());
                // 获取数据并填充 newData
                return dataList;
            }
            else
            {
                // 处理错误
                return new List<AlermModel>();  // 返回空列表
            }
        }
    }
}
